<template>
    <div class="deepseek-container">
        <!-- 左侧边栏（收起状态只显示Logo） -->
        <div class="sidebar-collapsed" v-if="sidebarCollapsed" @click="toggleSidebar">
            <div class="sidebar-logo">
                <el-icon :size="24">
                    <ChatDotRound />
                </el-icon>
            </div>
            <!-- <el-button class="collapse-btn" @click="toggleSidebar" circle size="large">
                <el-icon>
                    <ArrowLeft />
                </el-icon>
            </el-button>
            <el-button type="primary" size="large" class="new-chat-btn" @click="createNewSession">
                <el-icon class="new-chat-icon">
                    <Plus />
                </el-icon>新对话
            </el-button> -->
        </div>

        <!-- 左侧边栏（展开状态） -->
        <el-aside width="240px" class="session-list-container" v-show="!sidebarCollapsed">
            <div class="sidebar-header">
                <div class="sidebar-logo">
                    <!-- <el-icon :size="24"><ChatDotRound /></el-icon> -->
                    <span>DeepSeek</span>
                </div>
                <el-button class="collapse-btn" @click="toggleSidebar" circle size="large">
                    <el-icon>
                        <ArrowLeft />
                    </el-icon>
                </el-button>
                <el-button type="primary" size="large" class="new-chat-btn" @click="createNewSession">
                    <el-icon class="new-chat-icon">
                        <Plus />
                    </el-icon>新对话
                </el-button>
            </div>

            <el-scrollbar class="session-scrollbar">
                <div v-for="session in sessions" :key="session.sessionId" class="session-item"
                    :class="{ active: currentSessionId === session.sessionId }"
                    @click="selectSession(session.sessionId)">
                    <div class="session-content">
                        <div class="session-title">{{ session.title || '新会话' }}</div>
                        <div class="session-preview">{{ getSessionPreview(session.sessionId) }}</div>
                    </div>
                    <div class="session-actions">
                        <el-button type="danger" size="small" circle @click.stop="deleteSession(session.sessionId)">
                            <el-icon>
                                <Delete />
                            </el-icon>
                        </el-button>
                    </div>
                </div>
            </el-scrollbar>
        </el-aside>

        <!-- 右侧聊天区域 -->
        <el-main class="chat-main">
            <div v-if="!sessions || sessions.length === 0" class="welcome-message">
                <div class="welcome-content">
                    <h2>我是 小云老师，很高兴见到你！</h2>
                    <p>我可以帮你编写题库代码、优化系统功能、整理试题内容，还能生成各类考试题目和解析。无论是搭建题库平台还是完善试题管理，都可以交给我来协助！。</p>
                    <div class="welcome-actions">
                        <el-button type="primary" plain @click="selectLonin">欢迎登录</el-button>
                        <el-button type="primary" plain @click="createNewSession">访问交流</el-button>
                    </div>
                </div>
            </div>

            <div v-else class="chat-container">
                <el-scrollbar class="chat-scrollbar" ref="chatScrollbar">
                    <div class="chat-messages">
                        <div v-for="(msg, index) in currentMessages" :key="index" class="message-container">
                            <!-- AI消息 -->
                            <div class="ai-message" v-if="msg.type === 'ai'">
                                <div class="avatar ai-avatar">
                                    <el-avatar :size="36" src="https://img.icons8.com/color/48/cloud.png" />
                                </div>
                                <div class="message-content">
                                    <div class="bubble ai-bubble">
                                        <!-- <div class="message-text">{{ msg.answer }}</div> -->
                                        <!-- <div v-html="renderMarkdown(msg.answer)" class="message-text"></div> -->
                                        <div v-html="renderMarkdown(msg.answer)" class="markdown-body message-text" />
                                    </div>
                                </div>
                            </div>

                            <!-- 用户消息 -->
                            <div class="user-message" v-else>
                                <div class="avatar user-avatar">
                                    <el-avatar :size="36"
                                        :src="userData?.avatar?.trim() ? userData?.avatar : userAvatar()" />
                                </div>
                                <div class="message-content">
                                    <div class="bubble user-bubble">{{ msg.question }}</div>
                                </div>
                            </div>
                        </div>
                    </div>
                </el-scrollbar>


                <!-- 输入区域 -->
                <div class="chat-input-area">
                    <div class="input-container">
                        <el-input v-model="inputMessage" placeholder="给 DeepSeek 发送消息" class="message-input"
                            @keyup.enter="sendMessage" :disabled="isTyping">
                            <template #prefix>
                                <el-icon>
                                    <Edit />
                                </el-icon>
                            </template>
                        </el-input>
                        <el-button type="primary" class="send-button" @click="sendMessage"
                            :disabled="!inputMessage || isTyping" :loading="isTyping">
                            发送
                        </el-button>
                    </div>
                    <div class="footer-note">
                        <p>内容由 AI 生成，请仔细阅读</p>
                    </div>
                </div>
            </div>
        </el-main>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick } from 'vue';
import { OllamaApi } from '@/api/Ollama';
import { ElMessage } from 'element-plus';
import { useRouter } from 'vue-router';
import { userApi } from '@/api/Users';
import { UserData } from '@/types/UserData';
import { userAvatar } from '@/types/Base64Image';
import MarkdownIt from 'markdown-it';
import DOMPurify from 'dompurify'; // 安全过滤

import {
    Delete,
    ArrowLeft,
    Plus,
    Edit,
    ChatDotRound
} from '@element-plus/icons-vue';

interface Session {
    sessionId: string;
    title?: string;
    createdAt: string;
    updatedAt: string;
}

interface Message {
    // type: 'user' | 'ai';
    type: string
    question: string;
    answer: string;
    timestamp: string;
    isError?: boolean;
}



// 用户信息
const userData = ref<UserData>(null);
// 状态管理
const sessions = ref<Session[] | null>(null);       // 会话列表
const currentSessionId = ref<string | null>(null);  // 当前选中的会话ID
const currentMessages = ref<Message[]>([]);         // 当前会话消息
const inputMessage = ref('');                       // 输入框内容        
const isTyping = ref(false);                        // 是否正在输入            
const sidebarCollapsed = ref(true);                 // 侧边栏折叠状态            
const chatScrollbar = ref();                        // 聊天滚动条引用  
const router = useRouter();                         // 路由器实例


// Markdown 解析器配置
const md = new MarkdownIt({
    html: true,       // 允许 HTML 标签
    linkify: true,    // 自动转换链接
    typographer: true // 优化排版
});

// 渲染函数（带首行缩进处理）
const renderMarkdown = (text) => {
    if (!text) return '';
    // 添加首行缩进（替换开头为全角空格）
    const processedText = text.replace(/^/, '  ');
    const unsafeHtml = md.render(processedText);
    return DOMPurify.sanitize(unsafeHtml);
};

// 添加自动欢迎方法
const sendWelcomeMessage = async () => {
    const welcomeMsg = {
        type: 'ai',
        question: '',
        answer: '您好！我是小云助手，有什么题库相关的问题可以随时问我~',
        timestamp: new Date().toISOString()
    }

    currentMessages.value.push(welcomeMsg)
    scrollToBottom()
}

// 跳转登录
const selectLonin = () => {
    router.push({ name: 'login' });
};
// 选择会话
const selectSession = async (sessionId: string) => {
    currentSessionId.value = sessionId;
    await fetchChatHistory(sessionId);
    scrollToBottom();
};

// 获取会话预览
const getSessionPreview = (sessionId: string) => {
    const messages = currentMessages.value.filter(msg =>
        (msg.type === 'user' && msg.question) ||
        (msg.type === 'ai' && msg.answer)
    );
    const lastMessage = messages[messages.length - 1];
    return lastMessage ?
        (lastMessage.type === 'user' ? lastMessage.question : lastMessage.answer).slice(0, 20) + '...'
        : '暂无消息';
};

// 创建新的会话
const createNewSession = async (): Promise<Session> => {
    try {
        const response = await OllamaApi.createChat();
        // console.log('id:', response.data.sessionId);
        // console.log('创建会话响应:', response);
        const newSession: Session = {
            sessionId: response.data.sessionId,
            title: '新会话',
            createdAt: new Date().toISOString(),
            updatedAt: new Date().toISOString()
        };
        // console.log('新会话已创建:', newSession);
        sendWelcomeMessage()
        sessions.value.unshift(newSession);
        toggleSidebar();
        ElMessage.success('新会话已创建');
        return newSession;
    } catch (error) {
        console.error('创建会话失败:', error);
        ElMessage.error('创建会话失败');
        throw error; // 抛出错误以便上层处理
    }
};

// 获取会话列表
const fetchSessions = async () => {
    try {
        // 1. 调用API获取会话ID列表（添加null检查）
        const sessionList = (await OllamaApi.getChats()) || [];
        console.log('获取会话列表:', sessionList);

        // 2. 安全地转换会话ID数组
        // sessions.value = Array.isArray(sessionList)
        //     ? sessionList.map(sessionId => ({
        //         sessionId,
        //         createdAt: new Date().toISOString(),
        //         updatedAt: new Date().toISOString()
        //     }))
        //     : [];
        console.log('转换后的会话列表:', sessions.value);

        // 3. 处理空会话情况
        if (sessions.value.length === 0) {
            const newSession = await createNewSession();
            currentSessionId.value = newSession.sessionId;
            return; // 创建后直接返回
        }

        // 4. 有会话但未选择时自动选择第一个
        if (!currentSessionId.value) {
            currentSessionId.value = sessions.value[0].sessionId;
            await fetchChatHistory(currentSessionId.value);
        }
    } catch (error) {
        console.error('获取会话列表失败:', error);
        ElMessage.error('获取会话列表失败');
    }
};


// 获取聊天历史
const fetchChatHistory = async (sessionId: string) => {
    // try {
    //     const history = await OllamaApi.getChatHistory(sessionId);
    //     currentMessages.value = history.map(msg => ({
    //         type: 'ai',
    //         question: '',
    //         answer: msg.message,
    //         timestamp: new Date().toISOString()
    //     }));
    // } catch (error) {
    //     console.error('获取聊天记录失败:', error);
    // }
};

// 发送消息
const sendMessage = async () => {
    const message = inputMessage.value.trim();
    if (!message || !currentSessionId.value) return;

    // 添加用户消息
    currentMessages.value.push({
        type: 'user',
        question: message,
        answer: '',
        timestamp: new Date().toISOString()
    });

    inputMessage.value = '';
    isTyping.value = true;

    // 添加AI消息占位
    const aiMessage = {
        type: 'ai',
        question: message,
        answer: '',
        timestamp: new Date().toISOString()
    };
    currentMessages.value.push(aiMessage);

    try {
        await OllamaApi.sendGeneralMessage(
            {
                sessionId: currentSessionId.value,
                message: message
            },
            (chunk) => {
                // 直接更新最后一个AI消息的内容
                const lastAiMessage = currentMessages.value[currentMessages.value.length - 1];
                if (lastAiMessage && lastAiMessage.type === 'ai') {
                    lastAiMessage.answer += chunk.message;
                    // 强制触发响应式更新
                    currentMessages.value = [...currentMessages.value];
                }
                scrollToBottom();
            }
        );

        // 更新会话标题
        if (currentMessages.value.length === 2) {
            const session = sessions.value.find(s => s.sessionId === currentSessionId.value);
            if (session) {
                session.title = message.length > 20 ? message.substring(0, 20) + '...' : message;
                sessions.value = [...sessions.value]; // 强制更新
            }
        }
    } catch (error) {
        console.error('发送消息失败:', error);
        const lastAiMessage = currentMessages.value[currentMessages.value.length - 1];
        if (lastAiMessage && lastAiMessage.type === 'ai') {
            lastAiMessage.answer = "抱歉，发送消息时出现错误";
            lastAiMessage.isError = true;
            currentMessages.value = [...currentMessages.value];
        }
    } finally {
        isTyping.value = false;
        scrollToBottom();
    }
};

// 删除会话
const deleteSession = async (sessionId: string) => {
    try {
        await OllamaApi.deleteChat(sessionId);
        sessions.value = sessions.value.filter(s => s.sessionId !== sessionId);

        if (currentSessionId.value === sessionId) {
            currentSessionId.value = sessions.value[0]?.sessionId || null;
            currentMessages.value = [];
        }

        ElMessage.success('会话已删除');
    } catch (error) {
        console.error('删除会话失败:', error);
        ElMessage.error('删除会话失败');
    }
};

// 滚动到底部
const scrollToBottom = async () => {
    await nextTick();
    if (chatScrollbar.value) {
        chatScrollbar.value.setScrollTop(chatScrollbar.value.wrapRef.scrollHeight);
    }
};

// 切换边栏
const toggleSidebar = () => {
    sidebarCollapsed.value = !sidebarCollapsed.value;
};

// 初始化
onMounted(() => {
    userApi.getLoginUserData().then((res) => {
        userData.value = res;
    });
    fetchSessions();

    // 如果有会话ID但没消息，发送欢迎语
    // if (currentSessionId.value && currentMessages.value.length === 0) {
    //     sendWelcomeMessage()
    // }

    // 如果没有会话，先创建会话再发送欢迎语
    // else if (!currentSessionId.value) {
    //     createNewSession().then(() => {
    //         sendWelcomeMessage()
    //     })
    // }
});
</script>

<style scoped>
/* 导入 GitHub 风格的 Markdown 样式 */
/* @import 'github-markdown-css/github-markdown.css'; */

/* Markdown内容样式 */
.markdown-body.message-text {
    font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
    font-size: 15px;
    color: #333;
    line-height: 1.6;

    /* 段落样式 */
    p {
        margin: 0.5em 0;
        text-align: justify;
        text-indent: 2em;
        /* 首行缩进 */
    }

    /* 列表样式 */
    ul,
    ol {
        padding-left: 1.5em;
    }

    /* 代码块样式 */
    pre {
        background: #f8f8f8;
        padding: 10px;
        border-radius: 4px;
        overflow-x: auto;
    }

    /* 链接样式 */
    a {
        color: #1890ff;
        text-decoration: none;
    }
}



.deepseek-container {
    width: var(--width);
    height: 100%;
    margin-top: 20px;
    color: #24292e;
    display: flex;
    position: relative;
    background-color: #f5f7fa;
}

/* 左侧边栏 - 收起状态 */
.sidebar-collapsed {
    width: 60px;
    height: 100%;
    background-color: #fff;
    border-right: 1px solid #e6e6e6;
    display: flex;
    justify-content: center;
    padding-top: 20px;
    cursor: pointer;
    transition: all 0.3s ease;
}

.sidebar-collapsed:hover {
    background-color: #f5f7fa;
}

.sidebar-logo {
    display: flex;
    flex-direction: column;
    align-items: center;
    color: #4b6cb7;
    font-weight: bold;
}

/* 左侧边栏 - 展开状态 */
.session-list-container {
    width: 240px;
    height: 100%;
    background-color: #fff;
    border-right: 1px solid #e6e6e6;
    display: flex;
    flex-direction: column;
    transition: all 0.3s ease;
}

.sidebar-header {
    padding: 16px;
    display: flex;
    gap: 12px;
    border-bottom: 1px solid #e6e6e6;
    flex-wrap: wrap;
    justify-content: space-between;
}

.sidebar-header .sidebar-logo {
    display: flex;
    align-items: center;
    gap: 8px;
    font-size: 20px;
    color: #4b6cb7;
    font-weight: bold;
}

.new-chat-btn {
    width: 60%;
    height: 40px;
    margin: 5px;
    border-radius: 15px;
    margin-left: 1px;
}

.new-chat-icon {
    margin: 7px;
}

.collapse-btn {
    /* position: absolute; */
    right: -12px;
    top: 20px;
    background-color: #fff;
    border: 1px solid #e6e6e6;
    z-index: 1;
}

.collapse-btn:hover {
    background-color: #f5f7fa;
}

.session-scrollbar {
    flex: 1;
    height: 0;
}

.session-item {
    padding: 12px 16px;
    border-bottom: 1px solid #f0f0f0;
    cursor: pointer;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.session-item:hover {
    background-color: #f5f7fa;
}

.session-item.active {
    background-color: #e6f7ff;
}

.session-content {
    flex: 1;
    overflow: hidden;
}

.session-title {
    font-weight: 500;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    margin-bottom: 4px;
}

.session-preview {
    font-size: 12px;
    color: #999;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.session-actions {
    margin-left: 8px;
    opacity: 0;
    transition: opacity 0.3s;
}

.session-item:hover .session-actions {
    opacity: 1;
}

/* 右侧聊天区域 */
.chat-main {
    flex: 1;
    display: flex;
    flex-direction: column;
    padding: 0;
    height: 100%;
    position: relative;
    justify-content: flex-end;
}

.welcome-message {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: center;
    text-align: center;
    color: #606266;
}

.welcome-content {
    max-width: 600px;
    padding: 20px;
}

.welcome-content h2 {
    font-size: 28px;
    margin-bottom: 15px;
    color: #303133;
}

.welcome-content p {
    font-size: 16px;
    margin-bottom: 25px;
    line-height: 1.6;
}

.welcome-actions {
    display: flex;
    justify-content: center;
    gap: 16px;
    margin-bottom: 25px;
}

.ai-notice {
    font-size: 14px;
    color: #999;
}

.chat-container {
    height: 100%;
}

.chat-scrollbar {
    flex: 1;
    height: 87%;
    padding: 16px;
    padding-bottom: 80px;
    /* 为固定输入框留出空间 */
    overflow-y: auto;
}

.chat-container {
    height: 100%;
}

.chat-scrollbar {
    flex: 1;
    height: 87%;
    padding: 16px;
    padding-bottom: 80px;
    /* 为固定输入框留出空间 */
    overflow-y: auto;
}

.chat-messages {
    display: flex;
    flex-direction: column;
    gap: 24px;
    /* 增加消息间距 */
}

/* AI消息样式 */
.ai-message {
    display: flex;
    gap: 12px;
    margin-right: auto;
    max-width: 90%;
    /* 限制最大宽度 */
}

/* 用户消息样式 */
.user-message {
    display: flex;
    flex-direction: row-reverse;
    /* 头像在右，消息在左 */
    gap: 12px;
    margin-left: auto;
    max-width: 90%;
    /* 限制最大宽度 */
}

/* 消息内容容器 */
.message-content {
    max-width: calc(100% - 60px);
    /* 减去头像宽度和间隙 */
    margin-right: 1px;
}

/* 头像样式 */
.avatar {
    flex-shrink: 0;
    align-self: flex-start;
    /* 头像始终顶部对齐 */
    margin-top: 4px;
    /* 微调垂直位置 */
}

/* 气泡样式 - 宽度自适应内容 */
.bubble {
    padding: 10px 16px;
    border-radius: 18px;
    word-break: break-word;
    line-height: 1.5;
    display: inline-block;
    /* 使宽度自适应内容 */
    max-width: 100%;
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}

/* AI气泡 - 浅蓝色 */
.ai-bubble {


    background: #f0f2f5;
    border: 1px solid #e0e0e0;
    margin: 8px 0;
}

/* 用户气泡 - 浅橙色 */
.user-bubble {

    background: #e6f7ff;
    border: 1px solid #bae7ff;
}

/* 输入区域 */
.chat-input-area {
    position: sticky;
    bottom: 0;
    padding: 16px;
    background-color: #fff;
    border-top: 1px solid #e6e6e6;
    z-index: 100;
}

.input-container {
    display: flex;
    gap: 12px;
    align-items: center;
}

.message-input {
    flex: 1;
}

.message-input :deep(.el-input__inner) {
    border-radius: 20px;
    padding-left: 40px;
    height: 42px;
    line-height: 42px;
}

.send-button {
    border-radius: 20px;
    padding: 0 25px;
    height: 42px;
}

.footer-note {
    font-size: 12px;
    color: #999;
    text-align: center;
    margin-top: 8px;
}
</style>